package ru.dveriwell.intra.finplan.ui;

import java.math.BigDecimal;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import ru.dveriwell.intra.finplan.domain.Plandivision;
import ru.dveriwell.intra.finplan.domain.Planestimate;
import ru.dveriwell.intra.finplan.domain.Planunit;
import ru.dveriwell.intra.util.UserHierarchicalBeanContainer;

import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.util.BeanContainer;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Table;
import com.vaadin.ui.TextField;
import com.vaadin.ui.Tree;
import com.vaadin.ui.VerticalLayout;

public class AdminTabComposition extends CustomComponent {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3572358557504849182L;
	private HorizontalLayout mainLayout;
	private Tree unitTree;
	private Tree divisionTree;
	private VerticalLayout toolsVLayout;
	private Label selectedUnitLabel;
	private Label selectedDivisionLabel;
	private TextField estimateTextField;
	private Button estimateAddBtn;
	private Table estimatesTable;
	
	
	EntityManager entityManager;
	UserHierarchicalBeanContainer<Integer, Plandivision> divisionContainer;
	UserHierarchicalBeanContainer<Integer, Planunit> unitContainer;
	BeanContainer<Integer, Planestimate> estimateContainer;
	
	/**
	 * The constructor should first build the main layout, set the
	 * composition root and then do any custom initialization.
	 *
	 * The constructor will not be automatically regenerated by the
	 * visual editor.
	 */
	public AdminTabComposition() {
		buildMainLayout();
		addListeners();
		setCompositionRoot(mainLayout);
	}
	
	private void addListeners() {
		estimateAddBtn.addListener(new Button.ClickListener() {
			private static final long serialVersionUID = -8786239689012392223L;
			@Override
			public void buttonClick(ClickEvent event) {
				
				if (estimateTextField.getValue().toString().length() > 0) {
					
					Planestimate newEstimate = new Planestimate();
					newEstimate.setEsimateqty(new BigDecimal(estimateTextField.getValue().toString()));
					newEstimate.setPlandivision(divisionContainer.getItem(divisionTree.getValue()).getBean());
					newEstimate.setPlanunit(unitContainer.getItem(divisionTree.getValue()).getBean());
					entityManager.getTransaction().begin();
					entityManager.persist(newEstimate);
					estimateContainer.addBean(newEstimate);
					entityManager.getTransaction().commit();
					
				}
				
			}
		});
		
		divisionTree.addListener(new Tree.ValueChangeListener() {

			private static final long serialVersionUID = -7048852372139578065L;
			@Override
			public void valueChange(ValueChangeEvent event) {
				selectedDivisionLabel.setValue(divisionContainer.getItem(divisionTree.getValue()).getBean().getDivisionname());
			}
			
			
		});

		unitTree.addListener(new Tree.ValueChangeListener() {

			private static final long serialVersionUID = -8637196123845842517L;
			@Override
			public void valueChange(ValueChangeEvent event) {
				selectedUnitLabel.setValue(unitContainer.getItem(unitTree.getValue()).getBean().getCommonname());
			}
			
			
		});

		
	}

	private void buildMainLayout() {

		divisionTree = new Tree();
		divisionTree.setCaption("Структурные подразделения");
		divisionTree.setImmediate(true);
		divisionTree.setWidth("300px");
		divisionTree.setHeight("100%");
		
		unitTree = new Tree();
		unitTree.setCaption("Статьи расходов");
		unitTree.setImmediate(true);
		unitTree.setWidth("300px");
		unitTree.setHeight("100%");

		selectedDivisionLabel = new Label();
		selectedDivisionLabel.setCaption("Текущее подразделение");
		selectedDivisionLabel.setValue("Подразделение не выбрано");
		
		selectedUnitLabel = new Label();
		selectedUnitLabel.setCaption("Текущий элемент бюджета");
		selectedUnitLabel.setValue("Элемент не выбран");
		
		estimateTextField = new TextField();
		estimateTextField.setCaption("Новый норматив (ед. в год)");
		
		estimateAddBtn = new Button();
		estimateAddBtn.setCaption("Добавить норматив");
		
		estimatesTable = new Table();
		estimatesTable.setCaption("Нормативы");
		estimatesTable.setWidth("300px");
		
		toolsVLayout = new VerticalLayout();
		toolsVLayout.addComponent(selectedDivisionLabel);
		toolsVLayout.addComponent(selectedUnitLabel);
		toolsVLayout.addComponent(estimateTextField);
		toolsVLayout.addComponent(estimateAddBtn);
		toolsVLayout.addComponent(estimatesTable);
		
		mainLayout = new HorizontalLayout();
		mainLayout.setSizeFull();
		mainLayout.addComponent(divisionTree);
		mainLayout.addComponent(unitTree);
		mainLayout.addComponent(toolsVLayout);
		
	}
	
	public void bindData(EntityManager entityManager) {
		
		this.entityManager = entityManager;
		
		// заполнение дерева структурных подразделений		
		TypedQuery<Plandivision> getDivisionsQuery = entityManager.createQuery("select pd from Plandivision pd order by pd.divisionname", Plandivision.class);
		divisionContainer = new UserHierarchicalBeanContainer<Integer,Plandivision>(Plandivision.class, "parentid");
		divisionContainer.setBeanIdProperty("id");
		divisionContainer.addAll(getDivisionsQuery.getResultList());
		divisionTree.setContainerDataSource(divisionContainer);
		divisionTree.setItemCaptionPropertyId("divisionname");
		
		// заполнение дерева статей и подстатей
		TypedQuery<Planunit> getUnitsQuery = entityManager.createQuery("select pu from Planunit pu order by pu.unitcode, pu.unitname", Planunit.class);
		unitContainer = new UserHierarchicalBeanContainer<Integer,Planunit>(Planunit.class, "parentid");
		unitContainer.setBeanIdProperty("id");
		unitContainer.addAll(getUnitsQuery.getResultList());
		unitTree.setContainerDataSource(unitContainer);
		unitTree.setItemCaptionPropertyId("commonname");

		// заполнение списка нормативов
		TypedQuery<Planestimate> getEstimateQuery = entityManager.createQuery("select pe from Planestimate pe order by pe.id", Planestimate.class);
		estimateContainer = new BeanContainer<Integer,Planestimate>(Planestimate.class);
		estimateContainer.setBeanIdProperty("id");
		estimateContainer.addAll(getEstimateQuery.getResultList());
		estimatesTable.setContainerDataSource(estimateContainer);
		
	}

}
